﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Windows.Threading;

namespace ChessOnline
{
    public partial class GamesPage : Page
    {
        GamesManager gamesManager = new GamesManager();
        DispatcherTimer timer = new DispatcherTimer();

        public GamesPage()
        {
            InitializeComponent();            
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void GamesPage_Loaded(object sender, RoutedEventArgs e)
        {
            // Подписаться на события авторизации
            Authorization.Instance.ThrowAuthorizationCompleted += new Authorization.EventHandler(AuthorizationCompleted);
            gamesManager.ThrowGetGamesListCompleted += new GamesManager.EventHandler(GetGamesListCompleted);
            gamesManager.ThrowCreateJoinEnded += new GamesManager.EventHandler(CreateJoinGameEnded);
            Authorization.Instance.CheckAuthorization();

            // Инициализировать таймер, который будет запрашивать список доступных игр каждые 2 секунды
            // Через проверку авторизации
            timer.Interval = new TimeSpan(0, 0, 2);
            timer.Tick += new EventHandler(TimerTickEntryPoint);
            timer.Start();
        }

        void TimerTickEntryPoint(object sender, EventArgs e)
        {
            Authorization.Instance.CheckAuthorization();
        }

        private void AuthorizationCompleted(object sender, object args)
        {
            if (!Authorization.Instance.IsAuthorized())
            {// Если не авторизован, то перенаправляем на страницу авторизации
                NavigationService.Navigate(new Uri("/HomePage", UriKind.Relative));
            }
            else
            {// Если авторизован, запрашиваем список созданных свободных игр
                if (gamesManager.GetGameHash() == "")
                {// Если еще не создал и не присоединился к игре
                    gamesManager.GetGamesListAvailable();
                }
            }
        }

        private void GetGamesListCompleted(object sender, object args)
        {            
            List<ChessOnlineService.GameInfo> list = gamesManager.GetGamesList();
            int selected_item_index = gamesList.SelectedIndex;
            gamesList.Items.Clear();
            for (int i = 0; i < list.Count; i += 1)
            {
                ListBoxItem item = new ListBoxItem();
                item.Content = list[i].Creator_name;
                gamesList.Items.Add(item);
            }
            gamesList.SelectedIndex = selected_item_index;
            gamesList.Focus();            
        }

        private void createGameButton_Cliked(object sender, RoutedEventArgs e)
        {
            gamesManager.CreateGame();
        }

        private void joinGameButton_Clicked(object sender, RoutedEventArgs e)
        {
            if (gamesList.SelectedIndex != -1)
            {
                ListBoxItem lbi = gamesList.SelectedItem as ListBoxItem;
                gamesManager.JoinGame(lbi.Content.ToString());
            }
        }

        void CreateJoinGameEnded(object sender, object args)
        {
            if (gamesManager.GetGameHash() != "")
            {                
                NavigationService.Navigate(new Uri("/GamePage", UriKind.Relative));
            }
        }

        private void GamesPage_Unloaded(object sender, RoutedEventArgs e)
        {
            timer.Stop();
            timer.Tick -= new EventHandler(TimerTickEntryPoint);

            if (App.Session.ContainsKey("gamesManager"))
            {
                App.Session.Remove("gamesManager");                
            }

            App.Session.Add("gamesManager", gamesManager);
            Authorization.Instance.ThrowAuthorizationCompleted -= new Authorization.EventHandler(AuthorizationCompleted);
            gamesManager.ThrowGetGamesListCompleted -= new GamesManager.EventHandler(GetGamesListCompleted);
            gamesManager.ThrowCreateJoinEnded -= new GamesManager.EventHandler(CreateJoinGameEnded);            
        }
    }
}
